package com.cy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.pojo.*;
import com.cy.util.*;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

/**
 * Created by Administrator on 2017/7/19.
 */
@Service
public class QuartzService {

    private final Logger logger = LoggerFactory.getLogger(QuartzService.class);
    @Autowired
    private MyRedisService myRedisService;
    @Autowired
    private MongodbUtil mongodbUtil;



    /**
     * 处理资金流数据(处理秒级的数据)
     */
    public void secondHandle(){
        List<MongoZJSecondPojo> data = mongodbUtil.getData(null, MongoZJSecondPojo.class, MongoNamePojo.SECOND);
        for (MongoZJSecondPojo mongoZJSecondPojo : data){
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(mongoZJSecondPojo), HashMap.class);
            map.remove("second");
            String sum = (String) map.get("sum");
            map.remove("sum");
            String count = (String) map.get("count");
            map.remove("count");
            mongodbUtil.delte(map, MongoNamePojo.SECOND);
            map.remove("lastTid");
            List<MongoZJMinPojo> min = mongodbUtil.getData(map, MongoZJMinPojo.class, MongoNamePojo.MIN);
            Update update = new Update();
            if (min != null && !min.isEmpty()){
                MongoZJMinPojo m = min.get(0);
                update.set("count", BigDecimalUtil.add(count, m.getCount()));
                update.set("sum", BigDecimalUtil.add(sum, m.getSum()));
                mongodbUtil.update(map, MongoNamePojo.MIN, update);
            } else {
                MongoZJMinPojo m = JSON.parseObject(JSON.toJSONString(map), MongoZJMinPojo.class);
                m.setCount(count);
                m.setSum(sum);
                String time = "" + m.getYear() + getDoubleTime(m.getMonth()) + getDoubleTime(m.getDay()) + getDoubleTime(m.getHour()) + getDoubleTime(m.getMin());
                try {
                    m.setNowTime(ZJUtil.getNowTime(time));
                } catch (ParseException e) {
                    System.out.println("========================="+ time + "=========================");
                    e.printStackTrace();
                }
                mongodbUtil.insert(m, MongoNamePojo.MIN);
            }
        }
    }

    private String getDoubleTime(int time){
        if (time >= 10)
            return "" + time;
        return "0" + time;
    }

    /**
     * 处理资金流数据(处理分钟级的数据)
     */
    public void minHandle(){
        Map<String, Object> query = new HashMap<>();
        ZJUtil.getTimeHour(query);
        //获取当前小时的所有数据
        List<MongoZJMinPojo> data = mongodbUtil.getData(query, MongoZJMinPojo.class, MongoNamePojo.MIN);
        Map<String, MongoZJHourPojo> hourMap = new HashMap<>();
        for (MongoZJMinPojo mongoZJMinPojo : data){
            StringBuffer sb = new StringBuffer();
            sb.append(mongoZJMinPojo.getEx());
            sb.append(mongoZJMinPojo.getCoin());
            sb.append(mongoZJMinPojo.getYear());
            sb.append(mongoZJMinPojo.getMonth());
            sb.append(mongoZJMinPojo.getDay());
            sb.append(mongoZJMinPojo.getHour());
            sb.append(mongoZJMinPojo.getType());
            String key = sb.toString();
            if (hourMap.containsKey(key)){
                MongoZJHourPojo mongoZJHourPojo = hourMap.get(key);
                mongoZJHourPojo.setCount(BigDecimalUtil.add(mongoZJHourPojo.getCount(), mongoZJMinPojo.getCount()));
                mongoZJHourPojo.setSum(BigDecimalUtil.add(mongoZJHourPojo.getSum(), mongoZJMinPojo.getSum()));
                hourMap.put(key, mongoZJHourPojo);
            } else {
                MongoZJHourPojo mongoZJHourPojo = new MongoZJHourPojo();
                mongoZJHourPojo.setEx(mongoZJMinPojo.getEx());
                mongoZJHourPojo.setCoin(mongoZJMinPojo.getCoin());
                mongoZJHourPojo.setYear(mongoZJMinPojo.getYear());
                mongoZJHourPojo.setMonth(mongoZJMinPojo.getMonth());
                mongoZJHourPojo.setDay(mongoZJMinPojo.getDay());
                mongoZJHourPojo.setHour(mongoZJMinPojo.getHour());
                mongoZJHourPojo.setType(mongoZJMinPojo.getType());
                mongoZJHourPojo.setSum(mongoZJMinPojo.getSum());
                mongoZJHourPojo.setCount(mongoZJMinPojo.getCount());
                hourMap.put(key, mongoZJHourPojo);
            }
        }
        for (Map.Entry<String, MongoZJHourPojo> map : hourMap.entrySet()){
            MongoZJHourPojo mongoZJHourPojo = map.getValue();
            Map<String, Object> m = JSON.parseObject(JSON.toJSONString(mongoZJHourPojo), HashMap.class);
            m.remove("sum");
            m.remove("count");
            Update update = new Update();
            update.set("count", mongoZJHourPojo.getCount());
            update.set("sum", mongoZJHourPojo.getSum());
            mongodbUtil.updateInsert(m, MongoNamePojo.HOUR, update);
        }
    }

    /**
     * 处理资金流数据(处理小时级的数据)
     */
    public void hourHandle(){
        Map<String, Object> query = new HashMap<>();
        List<MongoZJHourPojo> data = mongodbUtil.getData(query, MongoZJHourPojo.class, MongoNamePojo.HOUR);
        Map<String, MongoZJDayPojo> dayMap = new HashMap<>();
        for (MongoZJHourPojo mongoZJHourPojo : data){
            StringBuffer sb = new StringBuffer();
            sb.append(mongoZJHourPojo.getEx());
            sb.append(mongoZJHourPojo.getCoin());
            sb.append(mongoZJHourPojo.getYear());
            sb.append(mongoZJHourPojo.getMonth());
            sb.append(mongoZJHourPojo.getDay());
            sb.append(mongoZJHourPojo.getType());
            String key = sb.toString();
            if (dayMap.containsKey(key)){
                MongoZJDayPojo mongoZJDayPojo = dayMap.get(key);
                mongoZJDayPojo.setCount(BigDecimalUtil.add(mongoZJDayPojo.getCount(), mongoZJHourPojo.getCount()));
                mongoZJDayPojo.setSum(BigDecimalUtil.add(mongoZJDayPojo.getSum(), mongoZJHourPojo.getSum()));
                dayMap.put(key, mongoZJDayPojo);
            } else {
                MongoZJDayPojo mongoZJDayPojo = new MongoZJDayPojo();
                mongoZJDayPojo.setEx(mongoZJHourPojo.getEx());
                mongoZJDayPojo.setCoin(mongoZJHourPojo.getCoin());
                mongoZJDayPojo.setYear(mongoZJHourPojo.getYear());
                mongoZJDayPojo.setMonth(mongoZJHourPojo.getMonth());
                mongoZJDayPojo.setDay(mongoZJHourPojo.getDay());
                mongoZJDayPojo.setType(mongoZJHourPojo.getType());
                mongoZJDayPojo.setSum(mongoZJHourPojo.getSum());
                mongoZJDayPojo.setCount(mongoZJHourPojo.getCount());
                dayMap.put(key, mongoZJDayPojo);
            }
        }
        for (Map.Entry<String, MongoZJDayPojo> map : dayMap.entrySet()){
            MongoZJDayPojo mongoZJDayPojo = map.getValue();
            Map<String, Object> m = JSON.parseObject(JSON.toJSONString(mongoZJDayPojo), HashMap.class);
            m.remove("sum");
            m.remove("count");
            Update update = new Update();
            update.set("count", mongoZJDayPojo.getCount());
            update.set("sum", mongoZJDayPojo.getSum());
            mongodbUtil.updateInsert(m, MongoNamePojo.DAY, update);
        }
    }

    /**
     * 3秒执行一次
     * @throws IllegalAccessException
     */
    public void execute3() throws IllegalAccessException {
        try {
            secondHandle();
        } catch (Exception e){
            e.printStackTrace();
            logger.info("===================================" + e.getMessage());
        }
    }

    private void clearMongoData(){
        Map<String, Object> map = new HashMap<>();
        map = ZJUtil.getbeforeDay(map);
        mongodbUtil.delte(map, MongoNamePojo.DAY);
        mongodbUtil.delte(map, MongoNamePojo.HOUR);
        mongodbUtil.delte(map, MongoNamePojo.MIN);
    }

    /**
     * 需要定时执行的放这里
     * 20秒一次
     */
    public void execute() throws IllegalAccessException {
        try{
            minHandle();
        } catch (Exception e){
            e.printStackTrace();
            logger.info("===================================" + e.getMessage());
        }
        try{
            hourHandle();
        } catch (Exception e){
            e.printStackTrace();
            logger.info("===================================" + e.getMessage());
        }
        try {
            ZJUtil.minHandle(mongodbUtil, myRedisService);
        } catch (Exception e){
            e.printStackTrace();
            logger.info("===================================" + e.getMessage());
        }
    }

    /**
     * 每天凌晨1点执行一次
     */
    public void oneDay(){
        clearMongoData();
    }
}